package com.yshebkb.sulp.controller;

import com.yshebkb.sulp.domain.LoginParam;
import com.yshebkb.sulp.domain.RestResponse;
import com.yshebkb.sulp.exception.AppException;
import com.yshebkb.sulp.utils.ShiroUtils;
import com.yshebkb.sulp.exception.ErrorCodes;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

/**
 * @author yshebkb
 */
@RestController
public class LoginController {

    @RequestMapping(value = "/api/login", method = {RequestMethod.POST})
    public RestResponse login(@RequestBody LoginParam loginParam) {
        Subject subject = ShiroUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginParam.getUsername(), loginParam.getPassword());
        try {
            subject.login(token);
            return RestResponse.success("登录成功");
        } catch (UnknownAccountException e) {
            throw new AppException(ErrorCodes.ACCOUNT_NOT_EXISTS);
        } catch (IncorrectCredentialsException e) {
            throw new AppException(ErrorCodes.WRONG_PASSWORD);
        }
    }


    /**
     * 退出
     */
    @RequestMapping(value = "/api/logout")
    public String logout() {
        ShiroUtils.logout();
        return "登出成功";
    }

    @RequestMapping(value = "/api/unauth")
    public String unauth() {
        ShiroUtils.logout();
        throw new AppException(ErrorCodes.UN_AUTH);
    }

}
